<?php
/**
 * Created by PhpStorm.
 * User: CY
 * Date: 2018/3/29
 * Time: 13:35
 */

namespace app\api\service;


use think\Exception;

class AccessToken
{
    private $tokenUrl;
    const TOKEN_CACHED_KEY = 'access';
    const TOKEN_EXPIRE_IN = 7000;

    function __construct() {
        $url = config('wx.access_token_url');
        $url = sprintf($url, config('wx.app_id'), config('wx.app_secret'));
        $this->tokenUrl = $url;
    }

    /**
     * 从缓存或者微信服务器中取得AccessToken
     * @return mixed|null
     */
    public function get() {
        $token = $this->getFromCache();
        if ($token) {
            return $token;
        } else {
            return $this->getFromWxServer();
        }
    }

    /**
     * 从缓存中获取token
     * @return mixed|null
     */
    private function getFromCache() {
        $token = cache(self::TOKEN_CACHED_KEY);
        if ($token) {
            return $token;
        }
        return null;
    }

    /**
     * 从微信服务器中获取AccessToken并存入缓存
     * @return mixed
     * @throws Exception
     */
    private function getFromWxServer() {
        $token = curl_get($this->tokenUrl);
        $token = json_decode($token, true);
        if (!$token) {
            throw new Exception('获取AccessToken异常');
        }
        if (!empty($token['errcode'])) {
            throw new Exception($token['errmsg']);
        }

        $this->saveToCache($token);
        return $token['access_token'];
    }

    /**
     * 将AccessToken存入缓存
     * @param $token
     */
    private function saveToCache($token) {
        cache(self::TOKEN_CACHED_KEY, $token, self::TOKEN_EXPIRE_IN);
    }
}